import pymysql
pymysql.install_as_MySQLdb()
from dataflow.conf import database_conf
import time
import traceback
import datetime
from common.logger import Logger

imei_db = pymysql.connect(**database_conf['imei_database'])
imei_cursor = imei_db.cursor()
logger = Logger("delete.log").getLogger()
logger.info('start ' + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))

try:
    min_max_sql = 'select min(id), max(id) from imei_score '
    imei_cursor.execute(min_max_sql)
    min_max_result = imei_cursor.fetchone()
    if min_max_result is not None:
        min_id = min_max_result[0]
        max_id = min_max_result[1]
        if min_id is None or max_id is None:
            logger.info('end ' + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))
            exit(0)
        logger.info(str(min_id) + ' ' + str(max_id))
        two_days_before = (datetime.datetime.now() - datetime.timedelta(days=5)).strftime('%Y-%m-%d %H:%M:%S')

        for id in range(min_id, max_id + 1):
            delete_sql = """ DELETE FROM imei_score WHERE id={0} AND is_expire = 1 AND utime < '{1}' """.format(id, two_days_before)
            logger.info(delete_sql)
            imei_cursor.execute(delete_sql)

except Exception as e:
    logger.info(traceback.format_exc())
finally:
    # 关闭数据库
    imei_db.close()

logger.info('end ' + str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())))

